package com.liu.dw.controller.word;

import com.liu.dw.service.word.FileResourcesService;
import com.liu.dw.service.word.WordService;
import com.liu.dw.vo.word.FileResources;
import com.liu.dw.vo.word.Wdoument;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hslf.record.Document;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 *
  文档下载
 *
 */
@Api(value="文档下载",tags = "文档下载")
@RestController
@RequestMapping("/document")
public class DownloadQueryController {

    @Autowired
    private FileResourcesService fileResourcesService;

    private WordService wordService;

    @ApiOperation(value = "word文档下载", notes = "word文档下载")
    @RequestMapping(value = "query", method = RequestMethod.POST)
    public void downloadLocal(Integer id, String wname, HttpServletResponse response) throws IOException {
        // 读到流中
        Wdoument file = fileResourcesService.getFile(id, wname);
        String wpath = file.getWpath();
        InputStream inputStream = new FileInputStream(wpath);// 文件的存放路径
        response.reset();
        response.setContentType("application/octet-stream");
        String filename = new File(wpath).getName();
        System.out.println(filename);
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }


    /**
     * 文档删除功能
     */
    @ApiOperation(value = "word文档删除", notes = "word文档删除")
    @DeleteMapping(value = "delete")
    public int deleteFile(Integer id) {
        int i = fileResourcesService.deleteFile(id);
        fileResourcesService.deletetable(id);
        fileResourcesService.deleteword(id);
        fileResourcesService.deleteimage(id);
        return i;
    }


    @ApiOperation(value = "word文档查看", notes = "word文档查看")
    @RequestMapping(value = "view", method = RequestMethod.POST)
    public void view(Integer id, String wordName) throws IOException {
        File imageFolderFile = new File("/Users/liuweigang/Desktop/temptest/word/wor");
        //转换后html存放的位置
        Wdoument file = fileResourcesService.getFile(id, wordName);
        String wordPath = file.getWpath();
        File f = new File(wordPath);
        if (!f.exists()) {
                         System.out.println("Sorry File does not Exists!");
                     } else {
            if (f.getName().endsWith(".docx") || f.getName().endsWith(".DOCX")) {
                // 1) 加载word文档生成 XWPFDocument对象
                InputStream in = new FileInputStream(f);
                XWPFDocument document = new XWPFDocument(in);

                // 2) 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)
                File imageFolder = new File(wordPath);
                XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolder));
                options.setExtractor(new FileImageExtractor(imageFolder));
                options.setIgnoreStylesIfUnused(false);
                options.setFragment(true);
                // 3) 将 XWPFDocument转换成XHTML
                OutputStream out = new FileOutputStream(new File(wordPath));
                XHTMLConverter.getInstance().convert(document, out, options);

                //也可以使用字符数组流获取解析的内容
                //                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                //                XHTMLConverter.getInstance().convert(document, baos, options);
                //                String content = baos.toString();
                //                System.out.println(content);
                //                 baos.close();
            } else {
                System.out.println("Enter only MS Office 2007+ files");
            }
        }
    }
}
